<template>
  <a-spin
    :loading="spinLoading"
    :size="35"
    class="w-[100%]"
    tip="正在处理, 请稍候..."
  >
    <div class="page-container">
      <!-- 操作按钮区域 -->
      <a-card :bordered="false" class="action-buttons-card mb-6">
        <div class="flex justify-between items-center">
          <div class="flex items-center space-x-2">
            <icon-info-circle class="text-blue-600" />
            <span class="text-sm text-gray-600">请填写完整购买记录信息后提交</span>
          </div>
          <a-space>
            <a-button type="primary" @click="onSubmit">
              <template #icon><icon-plus /></template>
              提交记录
            </a-button>
            <a-button @click="onCancel">
              <template #icon><icon-arrow-left /></template>
              返回
            </a-button>
          </a-space>
        </div>
      </a-card>

      <a-form
        ref="formRef"
        :model="form"
        :rules="getDynamicRules()"
        auto-label-width
        layout="vertical"
      >
        <!-- 基本信息区域 -->
        <a-card title="基本信息" :bordered="false" class="form-card">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item
                field="purchaseIndexRecordCode"
                label="编号"
                required
              >
                <a-input
                  v-model="form.purchaseIndexRecordCode"
                  placeholder="请输入编号"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="purchaseTime" label="购买时间" required>
                <a-date-picker
                  v-model="form.purchaseTime"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择购买时间"
                  show-time
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="remark" label="备注">
                <a-textarea
                  v-model="form.remark"
                  placeholder="请输入备注信息"
                  :max-length="500"
                  show-word-limit
                  :auto-size="{ minRows: 1, maxRows: 3 }"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 购买记录区域 -->
        <a-card title="购买记录信息" :bordered="false" class="form-card">
          <template #extra>
            <a-button type="primary" @click="addPurchaseItem">
              <template #icon>
                <icon-plus />
              </template>
              添加记录
            </a-button>
          </template>

          <div
            v-for="(item, index) in form.purchaseItems"
            :key="index"
            class="purchase-item"
          >
            <a-card size="small" class="purchase-item-card">
              <template #title>
                <a-space>
                  <icon-file-text />
                  记录 {{ index + 1 }}
                </a-space>
              </template>
              <template #extra>
                <a-button
                  v-if="form.purchaseItems.length > 1"
                  size="mini"
                  status="danger"
                  @click="removePurchaseItem(index)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </template>

              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-item
                    :field="`purchaseItems.${index}.townName`"
                    label="镇街名称"
                    required
                  >
                    <a-select
                      v-model="item.townName"
                      allow-clear
                      placeholder="请选择镇街名称"
                    >
                      <a-option
                        v-for="town in townOptions"
                        :key="town.code"
                        :value="town.name"
                      >
                        {{ town.name }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item
                    :field="`purchaseItems.${index}.townIndex`"
                    label="购买亩数"
                    required
                  >
                    <a-input
                      v-model="item.townIndex"
                      placeholder="请输入购买亩数"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <!-- 合同上传部分 -->
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-item
                    :field="`purchaseItems.${index}.fileId`"
                    label="合同文件"
                  >
                    <div class="contract-upload-section">
                      <!-- 已有合同文件展示 -->
                      <div
                        v-if="
                          item.existingContractFiles &&
                          item.existingContractFiles.length > 0
                        "
                        class="existing-files"
                      >
                        <a-typography-text type="secondary">
                          <icon-file /> 已上传文件
                        </a-typography-text>
                        <a-list
                          :bordered="false"
                          :grid="{ gutter: 12, column: 2 }"
                        >
                          <a-list-item
                            v-for="file in item.existingContractFiles"
                            :key="file.fileId"
                          >
                            <a-card size="small" hoverable>
                              <a-space>
                                <a-avatar :size="28" shape="square">
                                  <icon-file-pdf
                                    v-if="file.fileType === 'pdf'"
                                  />
                                  <icon-file-image
                                    v-else-if="
                                      ['jpg', 'png', 'jpeg'].includes(
                                        file.fileType
                                      )
                                    "
                                  />
                                  <icon-file v-else />
                                </a-avatar>
                                <div class="file-info">
                                  <a-typography-text class="file-name">
                                    {{ file.fileName }}
                                  </a-typography-text>
                                  <div class="file-actions">
                                    <a-space size="mini">
                                      <a-button
                                        size="mini"
                                        type="text"
                                        @click="downloadFile(file)"
                                      >
                                        下载
                                      </a-button>
                                      <a-button
                                        size="mini"
                                        type="text"
                                        @click="previewFile(file)"
                                      >
                                        预览
                                      </a-button>
                                      <a-button
                                        size="mini"
                                        type="text"
                                        status="danger"
                                        @click="removeContractFile(index, file)"
                                      >
                                        删除
                                      </a-button>
                                    </a-space>
                                  </div>
                                </div>
                              </a-space>
                            </a-card>
                          </a-list-item>
                        </a-list>
                      </div>

                      <!-- 合同文件上传组件 -->
                      <uploadFile
                        v-if="
                          !item.existingContractFiles ||
                          item.existingContractFiles.length === 0
                        "
                        :ref="`contractUploadRef${index}`"
                        :file-source="contractFileSource"
                        :limit="1"
                        :multiple="false"
                        accept=".pdf,.doc,.docx,.jpg,.png,.jpeg"
                        list-type="text"
                        source-type="proxy"
                        @upload-success="
                          (response) =>
                            handleContractUploadSuccess(response, index)
                        "
                      />
                    </div>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </div>
        </a-card>

        <!-- 附件材料 -->
        <a-card title="附件材料" class="mt-4">
          <!-- 已有附件展示区域 -->
          <div v-if="existingFiles.length > 0" class="existing-files mb-4">
            <a-typography-text type="secondary">
              <icon-file /> 已上传附件
            </a-typography-text>
            <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
              <a-list-item v-for="file in existingFiles" :key="file.fileId">
                <a-card size="small" hoverable>
                  <a-space>
                    <a-avatar :size="28" shape="square">
                      <icon-file-pdf v-if="file.fileType === 'pdf'" />
                      <icon-file-image
                        v-else-if="
                          ['jpg', 'png', 'jpeg'].includes(file.fileType)
                        "
                      />
                      <icon-file v-else />
                    </a-avatar>
                    <div class="file-info">
                      <a-typography-text class="file-name">
                        {{ file.fileName }}
                      </a-typography-text>
                      <div class="file-actions">
                        <a-space size="mini">
                          <a-button
                            size="mini"
                            type="text"
                            @click="downloadFile(file)"
                          >
                            下载
                          </a-button>
                          <a-button
                            size="mini"
                            type="text"
                            @click="previewFile(file)"
                          >
                            预览
                          </a-button>
                          <a-button
                            size="mini"
                            type="text"
                            status="danger"
                            @click="removeExistingFile(file)"
                          >
                            删除
                          </a-button>
                        </a-space>
                      </div>
                    </div>
                  </a-space>
                </a-card>
              </a-list-item>
            </a-list>
          </div>

          <uploadFile
            ref="attachmentsUploadFileRef"
            :file-source="fs"
            :limit="10"
            :multiple="true"
            accept=".jpg,.png,.jpeg,.pdf,.doc,.docx,.xls,.xlsx"
            list-type="text"
            source-type="proxy"
            @upload-success="handleUploadSuccess"
          />
        </a-card>
      </a-form>
    </div>
  </a-spin>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, watch, onMounted, onBeforeUnmount } from "vue";
import uploadFile from "~/components/uploadFile/index.vue";
import {
  addPurchaseIndexRecordApi,
  deletePurchaseIndexRecordFileByFileIdApi,
  getPurchaseIndexRecordByPurchaseIndexRecordIdApi,
  updatePurchaseIndexRecordByPurchaseIndexRecordIdApi,
} from "~/api/lindi/purchaseIndexRecord";
import { fileSource } from "~/utils/sys.js";
import {
  IconDelete,
  IconDownload,
  IconFile,
  IconFilePdf,
  IconFileImage,
  IconPlus,
  IconEye,
  IconInfoCircle,
  IconArrowLeft,
} from "@arco-design/web-vue/es/icon";
import { deleteFileApi } from "~/api/basic/file.js";

// 全局实例
const { proxy } = getCurrentInstance();

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit
const emit = defineEmits(["ok", "cancel"]);

// 加载状态
const spinLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 文件上传引用
const attachmentsUploadFileRef = ref(null);

// 文件来源
const fs = fileSource.lindi_purchase_record_file.key; // 使用购买记录附件的文件来源
const contractFileSource = fileSource.lindi_purchase_contract_file?.key || fs; // 合同文件来源

// 是否为编辑模式
const isEdit = ref(false);

// 已有附件列表
const existingFiles = ref([]);

// 跟踪新上传的文件ID，用于取消时清理
const newUploadedFileIds = ref([]);

// 检查表单是否有变更
const hasFormChanged = ref(false);

// 下载文件
function downloadFile(file) {
  window.open(file.fileUrl, "_blank");
}

// 删除已有附件
function removeExistingFile(file) {
  proxy.$modal.confirm({
    title: "确认删除",
    content: `确定要删除附件 "${file.fileName}" 吗？`,
    onOk: () => {
      spinLoading.value = true;
      // 调用后端API删除文件
      deletePurchaseIndexRecordFileByFileIdApi(file.fileId)
        .then(() => {
          // 从已有附件列表中移除
          existingFiles.value = existingFiles.value.filter(
            (item) => item.fileId !== file.fileId
          );

          // 从上传组件的文件列表中移除
          if (
            attachmentsUploadFileRef.value &&
            attachmentsUploadFileRef.value.fileList
          ) {
            attachmentsUploadFileRef.value.fileList =
              attachmentsUploadFileRef.value.fileList.filter(
                (item) => item.uid !== file.fileId
              );
          }

          // 从表单的fileIds中移除
          if (form.fileIds && Array.isArray(form.fileIds)) {
            form.fileIds = form.fileIds.filter((id) => id !== file.fileId);
          }

          proxy.$msg.success("附件删除成功");
        })
        .catch((error) => {
          proxy.$msg.error("删除附件失败: " + error.message);
        })
        .finally(() => {
          spinLoading.value = false;
        });
    },
  });
}

// 镇街选项数据
const townOptions = [
  { code: "350582001", name: "青阳街道" },
  { code: "350582002", name: "梅岭街道" },
  { code: "350582003", name: "新塘街道" },
  { code: "350582004", name: "罗山街道" },
  { code: "350582005", name: "灵源街道" },
  { code: "350582006", name: "永和镇" },
  { code: "350582007", name: "安海镇" },
  { code: "350582008", name: "东石镇" },
  { code: "350582009", name: "英林镇" },
  { code: "350582010", name: "金井镇" },
  { code: "350582011", name: "龙湖镇" },
  { code: "350582012", name: "深沪镇" },
  { code: "350582013", name: "西园街道" },
  { code: "350582014", name: "池店镇" },
  { code: "350582015", name: "陈埭镇" },
  { code: "350582016", name: "紫帽镇" },
  { code: "350582017", name: "内坑镇" },
  { code: "350582018", name: "西滨镇" },
];

// 表单数据
const form = reactive({
  purchaseIndexRecordCode: "",
  purchaseItems: [
    // 动态购买记录数组
    {
      townName: "",
      townIndex: "",
      fileId: null, // 合同文件ID
      existingContractFiles: [], // 已有合同文件
    },
  ],
  purchaseTime: "",
  fileIds: [], // 附件ID，使用数组存储
  remark: "", // 备注信息
});

// 表单验证规则
const rules = {
  purchaseIndexRecordCode: [
    { required: true, message: "编号不能为空" },
    { maxLength: 50, message: "编号长度不能超过50个字符" },
  ],
  purchaseTime: [{ required: true, message: "购买时间不能为空" }],
  remark: [{ maxLength: 500, message: "备注长度不能超过500个字符" }],
  // 动态验证规则会在组件中处理
};

// 动态验证规则生成函数
const getDynamicRules = () => {
  const dynamicRules = {};
  form.purchaseItems.forEach((item, index) => {
    dynamicRules[`purchaseItems.${index}.townName`] = [
      { required: true, message: "镇街名称不能为空" },
      { maxLength: 100, message: "镇街名称长度不能超过100个字符" },
    ];
    dynamicRules[`purchaseItems.${index}.townIndex`] = [
      { required: true, message: "购买亩数不能为空" },
      { maxLength: 50, message: "购买亩数长度不能超过50个字符" },
    ];
  });
  return { ...rules, ...dynamicRules };
};

// 监听参数变化
watch(
  () => props.params,
  () => {
    if (props.params.purchaseIndexRecordId) {
      isEdit.value = true;
      loadRecordInfo(props.params.purchaseIndexRecordId);
    } else {
      isEdit.value = false;
    }
  },
  { deep: true, immediate: true }
);

// 加载记录信息
function loadRecordInfo(purchaseIndexRecordId) {
  spinLoading.value = true;

  getPurchaseIndexRecordByPurchaseIndexRecordIdApi(purchaseIndexRecordId)
    .then((res) => {
      if (res) {
        // 处理后端返回的数据
        const data = { ...res };

        // 处理附件ID
        if (typeof data.fileIds === "string" && data.fileIds) {
          data.fileIds = data.fileIds.split(",");
        } else if (!Array.isArray(data.fileIds)) {
          data.fileIds = [];
        }

        // 处理购买记录项数据
        if (
          data.purchaseItems &&
          Array.isArray(data.purchaseItems) &&
          data.purchaseItems.length > 0
        ) {
          // 如果后端返回了购买记录项数据，使用后端数据
          data.purchaseItems = data.purchaseItems.map((item) => ({
            ...item,
            existingContractFiles: item.file ? [item.file] : [],
          }));
        } else {
          // 如果后端没有返回购买记录项数据，初始化默认项
          data.purchaseItems = [
            {
              townName: "",
              townIndex: "",
              fileId: null,
              existingContractFiles: [],
            },
          ];
        }

        // 处理附件列表，用于上传组件回显和已有附件展示
        if (data.files && Array.isArray(data.files) && data.files.length > 0) {
          console.log("后端返回的附件数据:", data.files);

          // 更新已有附件列表，用于展示
          existingFiles.value = data.files;

          // 将附件数据转换为上传组件需要的格式
          const fileList = data.files.map((item) => ({
            uid: item.fileId,
            name: item.fileName || item.name,
            url: item.fileUrl, // 设置url用于预览
            status: "done",
            response: { fileId: item.fileId }, // 设置response.fileId用于删除和获取文件ID
          }));

          console.log("转换后的文件列表:", fileList);
          // 设置附件上传组件的文件列表
          if (attachmentsUploadFileRef.value) {
            setTimeout(() => {
              attachmentsUploadFileRef.value.fileList = fileList;
            }, 0);
          }
        } else {
          // 如果没有附件，清空已有附件列表
          existingFiles.value = [];
        }

        Object.assign(form, data);
        
        // 数据加载完成后重置表单变更状态
        setTimeout(() => {
          hasFormChanged.value = false;
        }, 100);
      } else {
        proxy.$msg.error(res.msg || "获取购买指标记录详情失败");
      }
    })
    .catch((error) => {
      proxy.$msg.error("获取购买指标记录详情失败: " + error.message);
    })
    .finally(() => {
      spinLoading.value = false;
    });
}

// 提交表单
function onSubmit() {
  // 表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }

    // 获取上传文件的ID数组
    const fileIdStr = attachmentsUploadFileRef.value?.getUploadFileId() || "";
    // 将逗号分隔的字符串转换为数组（如果为空则使用空数组）
    const newFileIds = fileIdStr ? fileIdStr.split(",") : [];

    // 合并已有附件ID和新上传的附件ID
    // 从existingFiles中获取文件ID
    const existingFileIds = existingFiles.value.map((file) => file.fileId);

    // 合并去重
    form.fileIds = [...new Set([...existingFileIds, ...newFileIds])];

    // 处理购买记录项的合同文件ID
    form.purchaseItems.forEach((item, index) => {
      // 获取该项的合同文件上传组件
      const contractUploadRef = proxy.$refs[`contractUploadRef${index}`];
      if (contractUploadRef && contractUploadRef[0]) {
        const contractFileIdStr = contractUploadRef[0].getUploadFileId() || "";
        const newContractFileIds = contractFileIdStr
          ? contractFileIdStr.split(",")
          : [];

        // 获取已有合同文件ID
        const existingContractFileIds = item.existingContractFiles.map(
          (file) => file.fileId
        );

        // 合并已有合同文件ID和新上传的合同文件ID，取第一个作为fileId
        const allFileIds = [
          ...new Set([...existingContractFileIds, ...newContractFileIds]),
        ];
        item.fileId = allFileIds.length > 0 ? allFileIds[0] : null;
      }
    });

    // 处理日期格式
    if (form.purchaseTime && typeof form.purchaseTime === "object") {
      const date = new Date(form.purchaseTime);
      if (!isNaN(date.getTime())) {
        // 转换为LocalDateTime格式，确保包含时间部分
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        // 格式化为 yyyy-MM-dd HH:mm:ss
        form.purchaseTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    }

    // 添加
    if (!isEdit.value) {
      spinLoading.value = true;
      addPurchaseIndexRecordApi(form)
        .then(() => {
          proxy.$msg.success(proxy.operationType.add.success);
          hasFormChanged.value = false; // 重置表单变更状态
          newUploadedFileIds.value = []; // 清理文件ID列表
          emit("ok");
        })
        .finally(() => {
          spinLoading.value = false;
        });
    }
    // 修改
    else {
      spinLoading.value = true;
      updatePurchaseIndexRecordByPurchaseIndexRecordIdApi(form)
        .then(() => {
          proxy.$msg.success(proxy.operationType.update.success);
          hasFormChanged.value = false; // 重置表单变更状态
          newUploadedFileIds.value = []; // 清理文件ID列表
          emit("ok");
        })
        .finally(() => {
          spinLoading.value = false;
        });
    }
  });
}

// 取消
async function onCancel() {
  if (hasFormChanged.value) {
    proxy.$modal.confirm({
      title: "确认离开",
      content: "您有未保存的更改，确定要离开吗？",
      onOk: async () => {
        await cleanupUnusedFiles();
        emit("cancel");
      },
    });
  } else {
    await cleanupUnusedFiles();
    emit("cancel");
  }
}

// 清理未使用的文件
const cleanupUnusedFiles = async () => {
  for (const fileId of newUploadedFileIds.value) {
    try {
      await deleteFileApi(fileId);
    } catch (error) {
      console.error("删除文件失败:", error);
    }
  }
  newUploadedFileIds.value = [];
};

// 添加购买记录项
const addPurchaseItem = () => {
  form.purchaseItems.push({
    townName: "",
    townIndex: "",
    fileId: null,
    existingContractFiles: [],
  });
};

// 删除购买记录项
const removePurchaseItem = (index) => {
  if (form.purchaseItems.length > 1) {
    // 清理该项的合同文件
    const item = form.purchaseItems[index];
    if (item.fileId) {
      deleteFileApi(item.fileId).catch((error) => {
        console.error("删除合同文件失败:", error);
      });
    }
    form.purchaseItems.splice(index, 1);
  }
};

// 处理合同文件上传成功
const handleContractUploadSuccess = (response, itemIndex) => {
  if (response && response.fileId) {
    form.purchaseItems[itemIndex].fileId = response.fileId;

    // 将上传的文件添加到已存在文件列表中，以隐藏上传按钮
    if (!form.purchaseItems[itemIndex].existingContractFiles) {
      form.purchaseItems[itemIndex].existingContractFiles = [];
    }
    form.purchaseItems[itemIndex].existingContractFiles.push({
      fileId: response.fileId,
      fileName: response.fileName || response.name || "合同文件",
      fileUrl: response.fileUrl || response.url,
      fileType: response.fileType || "pdf",
    });

    if (!isEdit.value) {
      newUploadedFileIds.value.push(response.fileId);
    }

    // 强制更新组件以隐藏上传按钮
    proxy.$forceUpdate();

    proxy.$msg.success("合同文件上传成功");
  }
};

// 删除合同文件
const removeContractFile = (itemIndex, file) => {
  proxy.$modal.confirm({
    title: "确认删除",
    content: `确定要删除合同文件 "${file.fileName}" 吗？`,
    onOk: () => {
      spinLoading.value = true;
      deleteFileApi(file.fileId)
        .then(() => {
          // 从已有合同文件列表中移除
          const item = form.purchaseItems[itemIndex];
          if (item.existingContractFiles) {
            item.existingContractFiles = item.existingContractFiles.filter(
              (f) => f.fileId !== file.fileId
            );
          }

          // 清空合同文件ID
          if (item.fileId === file.fileId) {
            item.fileId = null;
          }

          // 强制更新组件以重新显示上传按钮
          proxy.$forceUpdate();

          proxy.$msg.success("合同文件删除成功");
        })
        .catch((error) => {
          proxy.$msg.error("删除合同文件失败: " + error.message);
        })
        .finally(() => {
          spinLoading.value = false;
        });
    },
  });
};

// 预览文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    proxy.$msg.warning("文件预览地址不存在");
  }
};

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  if (response && response.fileId && !isEdit.value) {
    newUploadedFileIds.value.push(response.fileId);
  }
  hasFormChanged.value = true;
};

// 页面离开前确认
const beforeUnloadHandler = (event) => {
  if (hasFormChanged.value) {
    event.preventDefault();
    event.returnValue = "您有未保存的更改，确定要离开吗？";
    return "您有未保存的更改，确定要离开吗？";
  }
};

// 监听表单变更
const watchFormData = () => {
  // 监听表单数据变化
  const stopWatcher = ref(null);
  
  const startWatching = () => {
    if (stopWatcher.value) {
      stopWatcher.value();
    }
    
    stopWatcher.value = watch(
      () => form,
      () => {
        hasFormChanged.value = true;
      },
      { deep: true }
    );
  };
  
  return { startWatching, stopWatcher };
};

const { startWatching } = watchFormData();

// 组件挂载时执行
onMounted(() => {
  // 添加页面离开前确认
  window.addEventListener("beforeunload", beforeUnloadHandler);
  
  // 延迟开始监听表单变更，避免初始化时触发
  setTimeout(() => {
    startWatching();
  }, 100);
});

// 组件卸载时清理
onBeforeUnmount(async () => {
  window.removeEventListener("beforeunload", beforeUnloadHandler);
  
  // 如果有未保存的文件，清理它们
  if (newUploadedFileIds.value.length > 0) {
    await cleanupUnusedFiles();
  }
});
</script>

<style scoped>
.mb-6 {
  margin-bottom: 24px;
}

.action-buttons-card {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.space-x-2 > * + * {
  margin-left: 8px;
}

.text-sm {
  font-size: 14px;
}

.text-blue-600 {
  color: #165dff;
}

.text-gray-600 {
  color: #6b7280;
}

.file-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  border: 1px dashed #d1d5db;
  padding: 16px;
  background-color: #f9fafb;
}

.existing-files-container {
  width: 100%;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e5e7eb;
}

.existing-files-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.existing-file-item {
  margin-bottom: 12px;
  width: 100%;
}

.existing-files {
  margin-bottom: 16px;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
}

.file-actions {
  margin-top: 4px;
}

.add-purchase-item-container {
  text-align: center;
  margin: 16px 0;
}

.contract-upload-section {
  padding: 8px 0;
}

/* 响应式布局优化 */
@media (max-width: 768px) {
  .purchase-item-card {
    padding: 16px;
    margin-bottom: 16px;
  }

  .add-purchase-item-container {
    padding: 12px;
  }
}
</style>
